package de.bloxel.ui;

import com.jme3.collision.CollisionResult;
import com.jme3.collision.CollisionResults;
import com.jme3.input.controls.ActionListener;
import com.jme3.math.Ray;
import com.jme3.math.Vector3f;

/**
 * @author hauschild
 * 
 */
public class BloxelActionController implements ActionListener {

  public static final String ATTACH_ACTION = "Shoot";
  public static final String DETACH_ACTION = "Detach";
  public static final String EXIT_ACTION = "Exit";

  private final BloxelApplication bloxelApplication;

  public BloxelActionController(final BloxelApplication theBloxelApplication) {
    bloxelApplication = theBloxelApplication;
  }

  @Override
  public void onAction(final String name, final boolean isPressed, final float tpf) {
    if (name.equals(EXIT_ACTION) && !isPressed) {
      bloxelApplication.stop();
    }
    if (name.equals(DETACH_ACTION) && !isPressed) {
      final CollisionResults results = new CollisionResults();
      final Ray ray = new Ray(bloxelApplication.getCamera().getLocation(), bloxelApplication.getCamera().getDirection());
      bloxelApplication.getBloxelsNode().collideWith(ray, results);
      if (results.size() > 0) {
        final CollisionResult closest = results.getClosestCollision();
        bloxelApplication.getBloxelsNode().detachChild(closest.getGeometry());
      }
    }
    if (name.equals(ATTACH_ACTION) && !isPressed) {
      // Reset results list.
      final CollisionResults results = new CollisionResults();
      // Aim the ray from cam loc to cam direction.
      final Ray ray = new Ray(bloxelApplication.getCamera().getLocation(), bloxelApplication.getCamera().getDirection());
      // Collect intersections between Ray and Shootables in results list.
      bloxelApplication.getBloxelsNode().collideWith(ray, results);
      // Use the results (we mark the hit object).
      if (results.size() > 0) {
        // The closest collision point is what was truly hit:
        final CollisionResult closest = results.getClosestCollision();
        final Vector3f contactNormal = closest.getContactNormal();
        final Vector3f targetPosition = new Vector3f(closest.getGeometry().getWorldBound().getCenter().add(contactNormal.mult(2)));
        // TODO pruefen ob an dieser neuen stelle bereits ein bloxel existiert
        bloxelApplication.addBloxel(targetPosition);
      }
    }
  }

}
